﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elderos.Ontology;

namespace Elderos.Highlight.Rules
{
    //Working hypothesis: word is english-like when it consists of frequently used english letter 3-grams.
    //The letter 3-grams are computed from 1000 most common english words.
    [RankingRule("SynonymEnglishLikeness", RuleType.Synonym)]
    public class RuleSynonymEnglishLikeness : SynonymRule
    {
        public RuleSynonymEnglishLikeness(IOntologyData ontology) : base(ontology) { }

        protected override IRuleResult ComputeResult(string synonym)
        {
            double coef = ComputeSynonymEnglishLikeness(synonym, Ontology);
            
            return new ContiniousResult(Name, coef);
        }

        private static double ComputeSynonymEnglishLikeness(string synonym, IOntologyData ontology)
        {
            string[] words = synonym.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            var coefs = new List<double>();

            foreach (var word in words)
            {
                if (word.Length < 3)
                    continue;

                int weightSum = 0;
                for (int i = 0; i < word.Length - 2; i++)
                {
                    string triple = word.Substring(i, 3).ToLower();
                    if (!ontology.Trigrams.ContainsKey(triple)) continue;
                    weightSum += ontology.Trigrams[triple];
                }

                //maximum triple count
                int normalizeCoef = word.Length - 2;

                coefs.Add(weightSum * 1.0 / normalizeCoef);
            }

            return coefs.Count > 0 ? coefs.Average() : 1;
        }

        public override IRuleResult EmptyResult
        {
            get { return new ContiniousResult(Name, 0);}
        }
    }
}
